/**
 * 路由规则
 */
// src/server.ts
import express, {ErrorRequestHandler, NextFunction, Request, Response, Express} from 'express'
import {config} from "./config/config";
import connectDB from "./db";
import logger from "./logger";
import {GamesModel} from "./models/gamesModel";
import {EcpmModel} from "./models/ecpmModel";
import {UsersModel} from "./models/usersModel";
import {getClientIp, getJson, setJson} from "./utils";
import {game_router} from "./routes/gameRouter";
import {ecpm_router} from "./routes/ecpmRouter";
import {user_router} from "./routes/userRouter";

require('express-async-errors');

connectDB().then(() => {
    const app: Express = express();
    app.use(express.json());
    app.use(express.urlencoded({extended: false}));
    app.use('*', (req: Request, res: Response, next: NextFunction) => {
        const ip = getClientIp(req);
        const url = req.originalUrl;
        const method = req.method;
        logger.info({ip, url, method});
        next();
    });
    app.use('/game', game_router);
    app.use('/ecpm', ecpm_router);
    app.use('/user', user_router);
    app.get('/users_all', async (req: Request, res: Response) => {
        res.json(await UsersModel.find());
    });
    app.get('/ecpms_all', async (req: Request, res: Response) => {
        res.json(await EcpmModel.find().limit(10));
    });
    app.get('/add', async (req: Request, res: Response) => {
        if (req.query.x) {
            const appid = req.query.x as string;
            let data = await getJson();
            data.push(appid);
            setJson(data);
            data = await getJson();
            res.json({
                appid: appid,
                data: data
            });
        } else {
            res.json('404');
        }
    });
    app.all('*', (req, res) => {
        res.status(404);
        res.json('not');
    })
    const errorHandler: ErrorRequestHandler = function (err, req, res, next) {
        try {
            logger.error(`throw ${err.stack}`);
            res.status(500).json({err: err.stack});
        } catch (error) {
            res.status(500).json(err.stack);
        }
    };
    app.use(errorHandler);
    app.listen(config.port, "0.0.0.0", () => {
        logger.info(`running ${config.port}`);
    });
});
